package com.ccsc.auth.controller;

import com.ccsc.auth.SystemException.IpCheckFailException;
import com.ccsc.auth.entity.*;
import com.ccsc.auth.entity.vi.UserVi;
import com.ccsc.auth.entity.vo.*;
import com.ccsc.auth.service.DepartmentService;
import com.ccsc.auth.service.PositionService;
import com.ccsc.auth.service.RoleService;
import com.ccsc.auth.service.UserService;
import com.ccsc.auth.utils.BaseResponse;
import com.ccsc.auth.utils.DataMap;
import com.ccsc.auth.utils.IpUtil;
import com.ccsc.auth.utils.Page;
import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static org.apache.tools.ant.types.selectors.SelectorUtils.match;

/**
 * Created by yyangs on 2017/2/17.
 */
@RestController
@RequestMapping("/userManage")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PositionService positionService;


    //获取全部用户信息通过列表分页
    @RequestMapping(value = "/usersBypages", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllUserBypages(WebRequest request,
                                          @RequestParam(required =false,defaultValue ="1")int page,
                                          @RequestParam(required =false,defaultValue ="10")int pageSize) throws Exception {
        DataMap params = getParam(request);
        params.put("page", page);
        params.put("pageSize", pageSize);
        try {
            List<Integer> departmentIds = new ArrayList<>();
            if(params.get("departmentId")!=null) {
                List<Department> departments = departmentService.getDepartmentsByParentDepartmentId(params.getInt("departmentId"));
                for (Department department:departments) {
                    departmentIds.add(department.getId());
                }
            }
            params.put("departmentIds",departmentIds);
            Page pageList = userService.getUsersByPage(params);
            List<User> userList = pageList.getContent();
            List<UserVo> userVoList = Lists.newArrayList();
            if(userList!=null && userList.size() > 0){
                int i=1+(params.getInt("page")-1)*params.getInt("pageSize");
                for(User user : userList){
                    UserVo userVo = new UserVo();
                    userVo.setNum(i++);
                    BeanUtils.copyProperties(userVo, user);
                    //封装类型和ip段
                    if(user.getVerify_type()!=null) {
                        if (user.getVerify_type() == 1 || user.getVerify_type() == 3) {
                            userVo.setPhoneVerify(1);
                        }
                    }
                    List<List<String>> ipVerify_value = Lists.newArrayList();
                    if(user.getVerify_value() != null && (user.getVerify_type() == 2|| user.getVerify_type() == 3 ) ){
                        String[] ipString = user.getVerify_value().split(",");
                        for(String string:ipString){
                            List<String> strings = Lists.newArrayList();
                            strings.add(string.split("-")[0]);
                            strings.add(string.split("-")[1]);
                            ipVerify_value.add(strings);
                        }
                    }
                    userVo.setIpVerify(ipVerify_value);

                    //添加部门信息
                    if(user.getPositionMap().size()>0) {
                        Map<Department, Position> departmentPositionMap = user.getPositionMap().get(0);
                        Iterator iter = departmentPositionMap.entrySet().iterator();
                        while (iter.hasNext()) {
                            Map.Entry entry = (Map.Entry) iter.next();
                            Department key = (Department) entry.getKey();
                            Position val = (Position) entry.getValue();
                            userVo.setRdopId(val.getRdop_id());
                            userVo.setDepartmentId(key.getId());
                            userVo.setDepartmentName(key.getName());
                            userVo.setPositionId(val.getId());
                            userVo.setPositionName(val.getName());
                        }
                    }
                    //添加角色信息
                    if(user.getRoleList().size()>0) {
                        List<RoleVo> roleVoList=new ArrayList<>();
                        for (Role role:user.getRoleList()) {
                            RoleVo roleVo=new RoleVo();
                            roleVo.setId(role.getId());
                            roleVo.setName(role.getName());
                            roleVoList.add(roleVo);
                        }
                        userVo.setRoles(roleVoList);
                    }
                    else{
                        userVo.setRoles(Lists.newArrayList());
                    }
                    userVoList.add(userVo);
                }
            }
            pageList.setContent(userVoList);
            return this.ok(pageList);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //获取全部角色列表
    @RequestMapping(value = "/roles", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllRole(WebRequest request) throws Exception {
        try {
            List<Role> roleList = roleService.getAllRoles();
            List<RoleVo> roleVos = Lists.newArrayList();
            if(roleList!=null && roleList.size() > 0){
                for(Role role : roleList){
                    RoleVo roleVo = new RoleVo();
                    BeanUtils.copyProperties(roleVo, role);
                    roleVos.add(roleVo);
                }
            }
            return this.ok(roleVos);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //查询用户详细信息根据id
    @RequestMapping(value = "/user/{userIdIn}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getUserById(@PathVariable("userIdIn")String userIdIn) throws Exception {
        Integer userId=Integer.parseInt(userIdIn);
        try {
            User user=userService.getUserById(userId);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(userVo, user);
            return this.ok(userVo);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //添加新用户
    @RequestMapping(value = "/user", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse addUser(WebRequest request, @Valid @RequestBody UserVi userVi, BindingResult bindingResult) throws Exception {
        try {
            Integer result=0;
            User user=userVi2User(userVi);
            //判断账号是否重复
            User userTemp=new User();
            List<User> users=userService.getUsersByAccount(user.getAccount());
            if(users.size()>0){
                return this.error(500,"用户账号已存在，请修改");
            }
            result = userService.createUser(user);
            return this.ok(result);
        }catch (IpCheckFailException e){
            ResponseData responseData = new ResponseData();
            responseData.setId(e.getId());
            responseData.setMessage(e.getMessage());
            List<ResponseData> responseDatas = Lists.newArrayList();
            responseDatas.add(responseData);
            return new BaseResponse(900,responseDatas);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //修改用户
    @RequestMapping(value = "/user/{userIdIn}", method = RequestMethod.PUT, produces = {"application/json", "application/xml"})
    public BaseResponse updateUser(@PathVariable("userIdIn")String userIdIn, @Valid @RequestBody UserVi userVi, BindingResult bindingResult) throws Exception {
        try {
            Integer result=0;
            userVi.setId(Integer.parseInt(userIdIn));
            User userTemp=userService.getUserById(userVi.getId());
            if(userTemp == null) {
                return this.error(500, "该用户不存在！");
            }

            User user=userVi2User(userVi);
            if(userTemp.getPassword().equals(userVi.getPassword())){
                user.setPassword(null);
            }
            //判断账号是否重复
            List<User> users=userService.getUsersByAccount(user.getAccount());
            if((users.size()==1&&!users.get(0).getId().equals(user.getId()))||users.size()>1){
                return this.error(500,"用户账号名称已存在，修改失败");
            }
            result = userService.updateUser(user);
            return this.ok(result);
        }catch (IpCheckFailException e){
            ResponseData responseData = new ResponseData();
            responseData.setId(e.getId());
            responseData.setMessage(e.getMessage());
            List<ResponseData> responseDatas = Lists.newArrayList();
            responseDatas.add(responseData);
            return new BaseResponse(900,responseDatas);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //删除用户
    @RequestMapping(value = "/user/{userIdIn}", method = RequestMethod.DELETE, produces = {"application/json", "application/xml"})
    public BaseResponse deleteUser(@PathVariable("userIdIn")String userIdIn) throws Exception {
        Integer userId=Integer.parseInt(userIdIn);
        try {
            Integer result=0;
            User user = userService.getUserById(userId);
            if(user!=null) {
                result= userService.deleteUserById(userId);
            }
            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //批量删除用户
    @RequestMapping(value = "/deleteUsers", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse deleteUsers(WebRequest request) throws Exception {
        DataMap params = getParam(request);
        String ids=(String) params.get("ids");
        try {
            Integer result=0;
            String[] strings=ids.split(",");
            for(int i=0;i<strings.length;i++){
                Integer userId=Integer.parseInt(strings[i]);
                User user = userService.getUserById(userId);
                if(user!=null) {
                    result= userService.deleteUserById(userId);
                }
            }
            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }


    //获取全部部门信息
    @RequestMapping(value = "/departments", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllDepartment(WebRequest request) throws Exception {
        try {
            List<DepartmentVo> depList = Lists.newArrayList();
            List<Department> departmentList = departmentService.getAllDepartments();
            if(departmentList!=null && departmentList.size()>0) {
                for (Department department : departmentList) {
                    DepartmentVo departmentVo = new DepartmentVo();
                    BeanUtils.copyProperties(departmentVo, department);
                    if(department.getParentDepartment()!=null) {
                        departmentVo.setpId(department.getParentDepartment().getId());
                    }
                    depList.add(departmentVo);
                }
            }
            return this.ok(depList);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }

    //获取全部职位信息
    @RequestMapping(value = "/positions", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllPosition(WebRequest request) throws Exception {
        try {
            List<PositionVo> posList = Lists.newArrayList();
            List<Position> positionList = positionService.getAllPositions();
            if(positionList!=null && positionList.size()>0){
                for(Position position : positionList){
                    PositionVo positionVo = new PositionVo();
                    positionVo.setId(position.getId());
                    positionVo.setName(position.getName());
                    posList.add(positionVo);
                }
            }
            return this.ok(posList);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(500, e.getMessage());
        }
    }
    public static User userVi2User(UserVi userVi) throws Exception{
        User user = new User();
        BeanUtils.copyProperties(user, userVi);
        //添加封装部门职位信息
        if(userVi.getDepartmentId()!=null&&userVi.getPositionId()!=null){
            Department department=new Department();
            department.setId(userVi.getDepartmentId());
            Position position=new Position();
            position.setId(userVi.getPositionId());
            position.setDepartment(department);
            position.setRdop_id(userVi.getRdopId());
            Map<Department,Position> departmentPositionMap=new ManagedMap<>();
            departmentPositionMap.put(department,position);
            List<Map<Department,Position>> mapList=new ArrayList<>();
            mapList.add(departmentPositionMap);
            user.setPositionMap(mapList);
        }
        //如果角色不为空，则添加角色
        if(userVi.getRoleIds().length!=0) {
            List<Role> roleList=new ArrayList<>();
            for (Integer i : userVi.getRoleIds()) {
                Role role = new Role();
                role.setId(i);
                roleList.add(role);
            }
            user.setRoleList(roleList);
        }else{
            throw new IpCheckFailException("roleIds","用户角色必填");
        }
        Integer vrify_type = 0;
        String vrify_value = "";
        if(userVi.getPhoneVerify() == 1){
            //表示当前是手机验证
            vrify_type += 1;
        }
        if(userVi.getIpVerify().size()>0){
            vrify_type += 2;
            //包含ip段验证 需要将list设置为字符串
            try {
                for (List<String> ipString : userVi.getIpVerify()) {
                    if("".equals(ipString.get(1))){
                        //如果后面的为空 则将前后一样
                        ipString.add(1,ipString.get(0));
                    }
                    //校验ip段
                    String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
                    String regex = "^" + num + "\\." + num + "\\." + num + "\\." + num + "$";
                    //验证ip符合规则
                    if (Pattern.matches(regex, ipString.get(0)) && Pattern.matches(regex, ipString.get(1))) {
                        //验证后面的ip大于前面的IP
                        if(IpUtil.getIp2long(ipString.get(1)) >= IpUtil.getIp2long(ipString.get(0))) {
                            vrify_value += "," + ipString.get(0) + "-" + ipString.get(1);
                        }else{
                            throw new IpCheckFailException("ipVerify","请确保IP段范围正确!");
                        }
                    }else{
                        throw new IpCheckFailException("ipVerify","IP或IP段填写错误,请更正!");
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
                throw new IpCheckFailException("ipVerify","IP或IP段填写错误,请更正!");
            }
        }
        user.setVerify_type(vrify_type);
//        if(vrify_type > 0) {
//            user.setVerify_type(vrify_type);
//            if (!"".equals(vrify_value)) {
//                user.setVerify_value(vrify_value.substring(1));
//            }
//        }else{
//            throw new IpCheckFailException("","验证方式必填");
//        }
        return user;
    }
//    public static void main(String[] args){
//        String ip = "127.0.0.1";
//        String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
//        String regex = "^" + num + "\\." + num + "\\." + num + "\\." + num + "$";
//        //验证ip符合规则
//
//        boolean isMatch = Pattern.matches(regex, ip);
//        System.out.print(isMatch);
//        int a =1;
//    }
}
